package com.ruoyi.web.rabbitmq;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class UserChangedService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserMapper userMapper;
    public synchronized void processUserChange(String queue, Message message, Channel channel, String finalAppId) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONUtil.parseObj(msg);
        //判断本 app 是否需要操作
        JSONArray appsArr = jsonObject.getJSONArray("apps");
        log.info("queue {}, finalAppId{}, apps {}", queue, finalAppId, JSONUtil.toJsonStr(appsArr));
        boolean flag = false;
        for (Object o : appsArr) {
            String appId = Convert.toStr(o);
            if (appId.equals(finalAppId)) {
                flag = true;
                break;
            }
        }
        log.info("finalAppId {} flag {}", finalAppId, flag);
        if (flag) {
            processUser(jsonObject);
        }
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException ex) {
            log.error("手动提交失败", ex);
        }
    }

    private void processUser(JSONObject jsonObject) {
        String operateType = jsonObject.getStr("operateType");
        log.info("operateType {}", operateType);
        JSONObject data = jsonObject.getJSONObject("data");
        log.info("data {}", JSONUtil.toJsonStr(data));
        SysUser user = new SysUser();
        user.setUserName(data.getStr("userName"));
        user.setNickName(data.getStr("nickName"));
        user.setEmail(data.getStr("email"));
        user.setPhonenumber(data.getStr("phonenumber"));
        user.setSex(data.getStr("sex"));
        user.setAvatar(data.getStr("avatar"));
        user.setPassword(data.getStr("password"));
        user.setStatus(data.getStr("status"));
        SysUser dbUser = userService.selectUserByUserName(user.getUserName());
        try {
            switch (operateType) {
                case "add":
                    //如果系统用户存在则更新用户,否则新增用户
                    if (null != dbUser) {
                        user.setUserId(dbUser.getUserId());
                        operateUpdate(user);
                    } else {
                        operateAdd(user);
                    }
                    break;
                case "update":
                    if (null == dbUser) {
                        operateAdd(user);
                    } else {
                        user.setUserId(dbUser.getUserId());
                        operateUpdate(user);
                    }
                    break;
                case "del":
                    if (null != dbUser) {
                        // admin用户没删除
                        if (!"admin".equals(dbUser.getUserName())) {
                            operateDel(dbUser.getUserId());
                        }
                    }
                    break;
                default:
                    log.info("不操作");
            }
        } catch (Exception e) {
            log.error("操作失败", e);
        }
    }

    /**
     * 添加操作
     *
     * @param user 用户
     */
    private void operateAdd(SysUser user) {
        log.info("operateAdd : user {}", JSONUtil.toJsonStr(user));
        int result = userMapper.insertUser(user);
        log.info("operateAdd : result {}", result);
    }

    /**
     * 更新操作
     *
     * @param user 用户
     */
    private void operateUpdate(SysUser user) {
        log.info("operateUpdate : user {}", JSONUtil.toJsonStr(user));
        int result = userMapper.updateUser(user);
        log.info("operateUpdate : result {}", result);
    }

    /**
     * 删除操作
     *
     * @param userId 用户id
     */
    private void operateDel(Long userId) {
        log.info("operateDel : user {}", userId);
        int result = userMapper.deleteUserById(userId);
        log.info("operateDel : result {}", result);
    }
}
